package com.example.unisys.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.unisys.common.Response;
import com.example.unisys.common.STATUS;
import com.example.unisys.entity.User;
import com.example.unisys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping(value = "/apis/v1/admins", produces = "application/json; charset=utf-8")
public class AdminController {
    @Autowired
    UserService userService;

    /*
     *查询该学校管理员
     * */
    @RequestMapping(value = "", method = {RequestMethod.GET})
    public Response getAdminsBySchool(@RequestParam("limit") int limit, @RequestParam("page") int page,
                                      @RequestParam("main_school") String main_school, @RequestParam("sub_school") String sub_school) {
        //系统管理员
        int newlimit = (page - 1) * limit;
        int pagesize = limit;
        HashMap<String, Object> hs1 = new HashMap<>();
        HashMap<String, Object> hs2 = new HashMap<>();
        hs1.put("main_school", main_school);
        hs1.put("start", newlimit);
        hs1.put("pagesize", pagesize);
        hs2.put("main_school", main_school);
        if (!main_school.equals(sub_school)) {
            hs1.put("sub_school", sub_school);
            hs2.put("sub_school", sub_school);
        }
        List<User> admins = userService.getAdminsBySchool(hs1);
        int sum = userService.getAdminSumBySchool(hs2);
        return Response.builder().status(STATUS.SUCCESS).total(sum).data(admins).build();
    }

    /*
     * 创建管理员
     * */
    @RequestMapping(value = "", method = {RequestMethod.POST})
    public Response createAdmin(@RequestBody JSONObject jsonParam) {
        User user = JSONObject.parseObject(jsonParam.toJSONString(), User.class);
        if (userService.insert(user) == 1)
            return Response.builder().status(STATUS.SUCCESS).build();
        return Response.builder().status(STATUS.BAD_REQUEST).message("插入失败").data("插入失败").build();
    }

    /*
     * 删除管理员
     * */
    @RequestMapping(value = "/{user_id}", method = {RequestMethod.DELETE})
    public Response delete(@PathVariable("user_id") int user_id) {
        if (userService.delete(user_id) == 1)
            return Response.builder().status(STATUS.SUCCESS).build();
        return Response.builder().status(STATUS.BAD_REQUEST).build();
    }

    /*
     * 修改管理员
     * */
    @RequestMapping(value = "", method = {RequestMethod.PUT})
    public Response update(@RequestBody JSONObject jsonParam) {
        User user = JSONObject.parseObject(jsonParam.toJSONString(), User.class);
        if (userService.update(user) == 1)
            return Response.builder().status(STATUS.SUCCESS).build();
        return Response.builder().status(STATUS.BAD_REQUEST).build();
    }

}

